const { app, Menu, Tray, shell, screen } = require('electron');
const { createTransparentWindow, createWindow } = require("../utils/window");

const { shellMenuDefaultController, getShellMenuController } = require("./menuController");

const program = require("../common/program");

const path = require('path');
const fs = require("fs");
const ioHook = require("iohook");

const RENDERER_PATH = path.join(__dirname, "../../renderer/");
const META_PATH = path.join(__dirname, "../meta/");

const { commonShortcutRegister } = require("../utils/shortcut");
const db = require("../database");
const spawn = require('child_process');
const Option = db.get('option').value();
const userDefineShell = db.get('userDefineShell').value();

const isMac = process.platform === 'darwin'

let { position, title, icon } = Option;
icon = icon.replace(/\$\{(\w+)\}/, (_, res) => eval(res));

function appReadyController() {
	/** main window */
	const { width, height } = screen.getPrimaryDisplay().workAreaSize;
	const screenSize = { ScreenWidth: width, ScreenHeight: height }
	let mainWindow = createTransparentWindow({
		x: eval(position.x.replace(/\$\{(\w+)\}/, (_, res) => screenSize[res])),
		y: eval(position.y.replace(/\$\{(\w+)\}/, (_, res) => screenSize[res]))
	});
	mainWindow.loadFile(RENDERER_PATH + "index.html");
	mainWindow.on('closed', function () {
		mainWindow = null
	});
	ioHook.start(false);
	let mouse_X = 0, mouse_Y = 0;
	ioHook.on('mousemove', (res) => {
		let { x, y } = res;
		mouse_X = x;
		mouse_Y = y;
		mainWindow.webContents.send("mouseevent", { x, y, width, height });
	});
	/* setInterval(_=>{
		spawn.exec(`screencapture -R ${mouse_X-20},${mouse_Y-20},40,40 ./src/renderer/static/imgs/meta/windowtemp.jpg`,(err)=>{
			if(err) {
				console.log(err);
			}
		});
	}, 100) */
	ioHook.on('mousedrag', (res) => {
		let { x, y } = res;
		mainWindow.webContents.send("mouseevent", { x, y, width, height });
	});
	ioHook.on('keydown', (res) => {
		// console.log(res);
		mainWindow.webContents.send("keyevent", res);
		if (res.keycode == 23 && res.metaKey && res.shiftKey) {
			mainWindow.webContents.openDevTools();
		}
	});
	ioHook.on('keyup', (res) => {
		mainWindow.webContents.send("keyevent", res);
	});
	/** menu */
	console.log(isMac);
	let menu = Menu.buildFromTemplate([
		// { role: 'appMenu' }
		...(isMac ? [{
			label: app.name,
			submenu: [
				{ role: 'about' },
				{ type: 'separator' },
				{ role: 'services' },
				{ type: 'separator' },
				{ role: 'hide' },
				{ role: 'hideOthers' },
				{ role: 'unhide' },
				{ type: 'separator' },
				{ role: 'quit' }
			]
		}] : []),
		// { role: 'editMenu' }
		{
			label: 'Edit',
			submenu: [
				{ role: 'undo' },
				{ role: 'redo' },
				{ type: 'separator' },
				{ role: 'cut' },
				{ role: 'copy' },
				{ role: 'paste' },
				{ role: 'delete' },
				{ role: 'selectAll' },
				{ type: 'separator' }
			]
		}
	]);
	Menu.setApplicationMenu(menu);

	/** 托盘 */
	program.appTray = new Tray(icon);
	let shellAdminWindow;
	program.appTrayMenuTemplate = [{
		id: 1,
		label: '小菜单demo',
		type: 'submenu',
		submenu: [
			{
				label: '默认',
				click: shellMenuDefaultController,
				checked: true,
				type: "radio"
			}, {
				type: 'separator'
			}, {
				label: '自定义脚本',
				click: function (res) {
					if (shellAdminWindow) {
						shellAdminWindow.show();
					} else {
						shellAdminWindow = createWindow({
							x: program.appTray.getBounds().x - 100,
							y: program.appTray.getBounds().y
						});
						shellAdminWindow.on('closed', function () {
							shellAdminWindow = null
						});
						shellAdminWindow.loadFile(RENDERER_PATH + "views/shellAdmin.html")
						shellAdminWindow.cl
						commonShortcutRegister(shellAdminWindow);
					}
				}
			}
		]
	}, {
		type: 'separator'
	}, {
		id: 2,
		label: '主面板',
		accelerator: 'CmdOrCtrl+,',
		click: function () {
			//let displays = electron.screen.getCursorScreenPoint()
			mainWindow.show();
			/* let systemWindow = createWindow({
				x: program.appTray.getBounds().x - 100,
				y: program.appTray.getBounds().y
			});
			systemWindow.loadFile(RENDERER_PATH + "views/system.html");
			systemWindowId = systemWindow.id; */
		}
	}, {
		type: 'separator'
	}, {
		label: 'about',
		click: function () {
			shell.openExternal("https://gitee.com/xuanyusan");
		}
	}, {
		label: 'sponsor',
		click: function (menuItem, browserWindow, event) {
			let wechatWindow = createWindow({
				x: program.appTray.getBounds().x - 100,
				y: program.appTray.getBounds().y,
				width: 300,
				height: 320
			});
			wechatWindow.loadFile(RENDERER_PATH + "views/reward.html")
		}
	}, {
		label: 'quit',
		accelerator: 'CmdOrCtrl+Q',
		role: 'quit'
	}];
	userDefineShell.forEach(item => {
		program.appTrayMenuTemplate[0].submenu.splice(1, 0, {
			label: item.label,
			click: getShellMenuController(item),
			type: "radio"
		});
	});
	contextMenu = Menu.buildFromTemplate(program.appTrayMenuTemplate);
	program.appTray.setContextMenu(contextMenu);
	// 标题
	program.appTray.setToolTip("design the shell script for yourself");
	program.appTray.setTitle(` \x1B[${title.color}m${title.label}\x1B[0m`);
}

function appBeforeQuitController() {
	ioHook.unload();
	ioHook.stop();
}

module.exports = {
	appReadyController,
	appBeforeQuitController
}